#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
from lxml import etree
import logging

from cvirt.cnode.libvirtXmlObject.cpu import CPU
from cvirt.cnode.libvirtXmlObject.baseDomain import XmlObject

LOG = logging.getLogger(__name__)

"""
    @author jay.han
"""
class Caps(XmlObject):
    ROOT_NAME = "capabilities"
    def __init__(self, parse_xml=None, **kw):
        super(Caps, self).__init__(parse_xml=parse_xml,**kw)
        self.host = None
        self.guests = []

    def _parse_xml(self, xmldoc):
        for c in xmldoc.getchildren():
            if c.tag == "host":
                host = CapsHost()
                host._parse_xml(c)
                self.host = host
            elif c.tag == "guest":
                guest = CapsGuest()
                guest._parse_xml(c)
                self.guests.append(guest)

    def _get_xml_config(self, root):

        if self.host:
            root.append(self.host.get_xml_config())
        for g in self.guests:
            root.append(g.get_xml_config())

        return root

class CapsHost(XmlObject):
    ROOT_NAME = "host"
    def __init__(self, parse_xml=None, **kw):
        super(CapsHost, self).__init__(parse_xml=parse_xml,**kw)

        self.cpu = None
        self.uuid = None

    def _parse_xml(self, xmldoc):
        for c in xmldoc.getchildren():
            if c.tag == "cpu":
                cpu = CPU()
                cpu._parse_xml(c)
                self.cpu = cpu
            elif c.tag == "uuid":
                self.uuid = c.text

    def _get_xml_config(self, root):
        if self.uuid:
            root.append(self._set_text("uuid", self.uuid))
        if self.cpu:
            root.append(self.cpu.get_xml_config())

        return root

class CapsGuest(XmlObject):
    ROOT_NAME = "guest"
    def __init__(self, parse_xml=None, **kw):
        super(CapsGuest, self).__init__(parse_xml=parse_xml,**kw)

        self.arch = None
        self.ostype = None
        self.domtype = list()

    def _parse_xml(self, xmldoc):
        for c in xmldoc.getchildren():
            if c.tag == "os_type":
                self.ostype = c.text
            elif c.tag == "arch":
                self.arch = c.get("name")
                for sc in c.getchildren():
                    if sc.tag == "domain":
                        self.domtype.append(sc.get("type"))

    def _get_xml_config(self, root):
        if self.ostype is not None:
            root.append(self._set_text("os_type", self.ostype))
        if self.arch:
            arch = etree.Element("arch", name=self.arch)
            for dt in self.domtype:
                dte = etree.Element("domain")
                dte.set("type", dt)
                arch.append(dte)
            root.append(arch)

        return root
